package api;

import Dao.User;
import Dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        // 获取账户密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || "".equals(username) || password == null || "".equals(password)){
            resp.getWriter().write("<script>alert('用户名密码不能为空!')</script>");
            return;
        }

        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user == null){
            resp.getWriter().write("<script>alert('用户不存在!')</script>");
            return;
        }
        if(!password.equals(user.getPassWord())){
            resp.getWriter().write("<script>alert('用户名密码错误!')</script>");
            return;
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        resp.sendRedirect("home.html");
    }
}
